/**
 * Created by chengxiaolong on 2016/6/22.
 */
package com.invexer.service.common {
import com.invexer.service.util.CursorUtil;

import mx.rpc.AbstractOperation;
import mx.rpc.AsyncToken;
import mx.rpc.Responder;
import mx.rpc.events.FaultEvent;
import mx.rpc.events.InvokeEvent;
import mx.rpc.events.ResultEvent;
import mx.rpc.soap.LoadEvent;
import mx.rpc.soap.WebService;
import mx.utils.ObjectUtil;

import org.as3commons.logging.ILogger;

import org.as3commons.logging.LoggerFactory;

public class InvexerWebService extends WebService{
    private static var logger : ILogger = LoggerFactory.getClassLogger(InvexerWebService);

    public function InvexerWebService(destination:String) {
        super();
        addEventListener(LoadEvent.LOAD, onLoad);
        addEventListener(InvokeEvent.INVOKE, onInvoke);
        addEventListener(FaultEvent.FAULT, onFault);
        addEventListener(ResultEvent.RESULT, onSuccess);
        wsdl = destination + "?wsdl";
        loadWSDL();

    }

    private function onLoad(event:LoadEvent):void{
        logger.info("onLoad");
    }

    private function onInvoke(event:InvokeEvent):void{
        logger.info("onInvoke");
    }

    private function onFault(event:FaultEvent):void{
        logger.error(ObjectUtil.toString(event));
    }

    private function onSuccess(event:ResultEvent):void{
        logger.info("onSuccess");
    }

    public function call(api:String, params:Object, successCallback:Function, failCallback:Function, useBusyCursor:Boolean=false):void{
        logger.info("api: " + api);
        logger.info("params: " + ObjectUtil.toString(params));

        if(useBusyCursor) CursorUtil.showBusyCursor();

        var operation:AbstractOperation = getOperation(api);
        var asyncToken:AsyncToken = operation.send(params);
        asyncToken.addResponder(new Responder(onSuccessCallback, onFaultCallback));

        function onSuccessCallback(event:ResultEvent):void{
            if(useBusyCursor) CursorUtil.removeBusyCursor();
            successCallback(event.result);
        }

        function onFaultCallback(event:FaultEvent) {
            if(useBusyCursor) CursorUtil.removeBusyCursor();
            failCallback(event);
        }
    }
}
}
